<template>
  <v-container fluid class="roleManagement-container">
    <v-tabs v-if="null != userInfo && null === this.userInfo.switchTenantId &&
      this.userInfo.tenantId === '0'" v-model="activeName" @update:model-value="tagClick">
      <v-tab v-for="item in $getDictList('menu_role_label')" :key="item.dictValue" :value="item.dictValue">
        {{ item.dictName }}
      </v-tab>
    </v-tabs>



    <!-- 工具栏 -->
    <v-card class="mb-4" elevation="10">
      <v-card-text>

        <v-row align="center">
          <v-col cols="12" md="6">

            <v-btn v-if="$perms('system_role_insert')" color="primary" prepend-icon="mdi-plus" @click="handleInsert"
              class="mr-2">添加</v-btn>
            <v-btn v-if="$perms('system_role_delete')" color="error" prepend-icon="mdi-delete"
              :disabled="!selectRows.length" @click="handleDelete">批量删除</v-btn>
          </v-col>
          <v-col cols="12" md="6">
            <v-row>
              <v-col>
                <v-text-field v-model.trim="queryForm.roleCode_EQ" placeholder="请输入角色编号" density="compact"
                  variant="outlined" hide-details clearable prepend-inner-icon="mdi-identifier"></v-text-field>
              </v-col>
              <v-col>
                <v-text-field v-model.trim="queryForm.roleName_LIKE" placeholder="请输入角色名称" density="compact"
                  variant="outlined" hide-details clearable prepend-inner-icon="mdi-account"></v-text-field>
              </v-col>
              <v-col cols="auto">
                <v-btn color="primary" prepend-icon="mdi-magnify" @click="queryData">查询</v-btn>
              </v-col>
            </v-row>
          </v-col>
        </v-row>
      </v-card-text>
    </v-card>

    <!-- 数据表格 -->
    <v-card elevation="10">
      <v-data-table v-model:items-per-page="queryForm.pageSize" :headers="headers" :items="list" :loading="listLoading"
        :items-length="total" @update:options="handleTableUpdate" show-select @update:model-value="setSelectRows"
        class="elevation-0">
        <template v-slot:item.dataScope="{ item }">
          {{ $getDictNameByValue('role_data_scope', item.dataScope) }}
        </template>

        <template v-slot:item.actions="{ item }">
          <v-btn v-if="$perms('system_role_update')" variant="text" color="primary" size="small"
            @click="handleUpdate(item)" class="mr-2">编辑</v-btn>
          <v-menu>
            <template v-slot:activator="{ props }">
              <v-btn variant="text" v-bind="props" size="small">
                更多
                <v-icon>mdi-chevron-down</v-icon>
              </v-btn>
            </template>
            <v-list>
              <v-list-item v-if="$perms('system_role_setMenuPerms')" @click="setPerms(item)"
                prepend-icon="mdi-shield-account">
                <v-list-item-title>授权菜单权限</v-list-item-title>
              </v-list-item>
              <v-list-item v-if="$perms('system_role_delete')" @click="handleDelete(item)" prepend-icon="mdi-delete"
                color="error">
                <v-list-item-title>删除</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu>
        </template>
      </v-data-table>
    </v-card>

    <edit ref="edit" @fetchData="fetchData"></edit>
    <menu-perms ref="perms"></menu-perms>
  </v-container>
</template>

<script>
import { getList, doDelete, doDeleteAll } from "@/api/system/role/roleManagement";
import { getUserInfo } from "@/api/user"
import Edit from "./components/RoleManagementEdit.vue";
import MenuPerms from "./components/RoleManagementMenuPerms.vue";
import { isNull } from "@/utils/validate";
import { useMessage } from "@/composables/useMessage";

export default {
  name: "RoleManagement",
  components: { Edit, MenuPerms },
  setup() {
    const { success: showSuccess, error: showError } = useMessage();
    return {
      showSuccess,
      showError
    };
  },
  data() {
    return {
      activeName: "1",
      userInfo: {},
      list: [],
      listLoading: true,
      total: 0,
      selectRows: [],
      headers: [
        { title: '角色编号', key: 'roleCode', sortable: false },
        { title: '角色名称', key: 'roleName', sortable: false },
        { title: '数据范围', key: 'dataScope', sortable: false },
        { title: '备注', key: 'remark', sortable: false },
        { title: '操作', key: 'actions', sortable: false, align: 'end' }
      ],
      queryForm: {
        pageNo: 1,
        pageSize: 10,
        roleCode_EQ: "",
        roleName_LIKE: "",
        label_EQ: "",
      },
    };
  },
  async created() {
    this.queryForm.label_EQ = this.activeName;

    // 预加载字典数据
    await this.preloadDictionaries();

    this.getCurrUser();
    this.fetchData();
  },
  methods: {
    /**
     * 预加载字典数据
     */
    async preloadDictionaries() {
      try {
        // 预加载需要的字典
        const dictTypes = ['menu_role_label', 'role_data_scope'];
        const promises = dictTypes.map(typeCode => this.$getDictListAsync(typeCode));
        await Promise.all(promises);
        console.log('字典数据预加载完成');
      } catch (error) {
        console.error('字典数据预加载失败:', error);
      }
    },

    // Tag 点击
    tagClick(tab) {
      this.queryForm.label_EQ = this.activeName;
      this.fetchData();
    },

    // 设置权限
    setPerms(row) {
      if (!row) {
        this.showError("请选择操作用户");
      }
      this.$refs["perms"].showPerms(row, this.activeName);
    },

    setSelectRows(val) {
      this.selectRows = val;
    },

    handleInsert() {
      this.$refs["edit"].showEdit(null, this.activeName);
    },

    handleUpdate(row) {
      if (row.id) {
        this.$refs["edit"].showEdit(row, this.activeName);
      }
    },

    handleDelete(row) {
      if (row.id) {
        // TODO: 需要实现确认对话框
        const confirmed = confirm("你确定要删除当前项吗");
        if (confirmed) {
          this.deleteItem(row.id);
        }
      } else {
        if (this.selectRows.length > 0) {
          const ids = this.selectRows.map((item) => item.id).join();
          const confirmed = confirm("你确定要删除选中项吗");
          if (confirmed) {
            this.deleteMultipleItems(ids);
          }
        } else {
          this.showError("未选中任何行");
          return false;
        }
      }
    },

    async deleteItem(id) {
      try {
        const response = await doDelete({ id });
        this.showSuccess(response.data?.msg || "删除成功");
        await this.fetchData();
      } catch (error) {
        this.showError("删除失败");
        console.error(error);
      }
    },

    async deleteMultipleItems(ids) {
      try {
        const response = await doDeleteAll({ ids });
        this.showSuccess(response.data?.msg || "批量删除成功");
        await this.fetchData();
      } catch (error) {
        this.showError("批量删除失败");
        console.error(error);
      }
    },

    handleTableUpdate(options) {
      this.queryForm.pageSize = options.itemsPerPage;
      this.queryForm.pageNo = options.page;
      this.fetchData();
    },

    queryData() {
      this.queryForm.pageNo = 1;
      this.fetchData();
    },

    async fetchData() {
      this.listLoading = true;
      try {
        const { data } = await getList(this.queryForm);
        this.list = data.rows;
        this.total = data.total;
      } catch (error) {
        console.error(error);
      } finally {
        this.listLoading = false;
      }
    },

    async getCurrUser() {
      try {
        const { data } = await getUserInfo();
        this.userInfo = data;
      } catch (error) {
        console.error(error);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.roleManagement-container {
  padding: 20px;
}
</style>
